from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException, AuthException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.dao.key_dao import KeyDao
from module_admin.entity.vo.key_vo import DeleteKeyModel, KeyModel, KeyPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil
from fastapi import Header, Request, Depends
from config.get_db import get_db
from redis.asyncio import Redis
from config.enums import RedisInitKeyConfig


class KeyService:
    """
    API-KEY模块服务层
    """

    @classmethod
    async def get_key_list_services(
        cls,
        query_db: AsyncSession,
        query_object: KeyPageQueryModel,
        is_page: bool = False,
    ):
        """
        获取API-KEY列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: API-KEY列表信息对象
        """
        key_list_result = await KeyDao.get_key_list(query_db, query_object, is_page)

        return key_list_result

    @classmethod
    async def check_api_key_unique_services(
        cls, query_db: AsyncSession, page_object: KeyModel
    ):
        """
        检查API-KEY是否唯一service

        :param query_db: orm对象
        :param page_object: API-KEY对象
        :return: 校验结果
        """
        id = -1 if page_object.id is None else page_object.id
        key = await KeyDao.get_key_detail_by_info(
            query_db, KeyModel(apiKey=page_object.api_key)
        )
        if key and key.id != id:
            return CommonConstant.NOT_UNIQUE
        return CommonConstant.UNIQUE

    @classmethod
    async def add_key_services(
        cls, redis: Redis, query_db: AsyncSession, page_object: KeyModel
    ):
        """
        新增API-KEY信息service

        :param query_db: orm对象
        :param page_object: 新增API-KEY对象
        :return: 新增API-KEY校验结果
        """
        if not await cls.check_api_key_unique_services(query_db, page_object):
            raise ServiceException(
                message=f"新增API-KEY{page_object.api_key}失败，API-KEY已存在"
            )
        try:
            await KeyDao.add_key_dao(query_db, page_object)
            await query_db.commit()
            # 再添加 Redis
            await redis.set(
                f"{RedisInitKeyConfig.OCR_API_KEY.key}:{page_object.api_key}",
                page_object.api_key,
            )
            return CrudResponseModel(is_success=True, message="新增成功")
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_key_services(cls, query_db: AsyncSession, page_object: KeyModel):
        """
        编辑API-KEY信息service

        :param query_db: orm对象
        :param page_object: 编辑API-KEY对象
        :return: 编辑API-KEY校验结果
        """
        edit_key = page_object.model_dump(
            exclude_unset=True,
            exclude={
                "user_id",
            },
        )
        key_info = await cls.key_detail_services(query_db, page_object.id)
        if key_info.id:
            if not await cls.check_api_key_unique_services(query_db, page_object):
                raise ServiceException(
                    message=f"修改API-KEY{page_object.api_key}失败，API-KEY已存在"
                )
            try:
                await KeyDao.edit_key_dao(query_db, edit_key)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message="更新成功")
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message="API-KEY不存在")

    @classmethod
    async def delete_key_services(
        cls, redis: Redis, query_db: AsyncSession, page_object: DeleteKeyModel
    ):
        """
        删除API-KEY信息service

        :param query_db: orm对象
        :param page_object: 删除API-KEY对象
        :return: 删除API-KEY校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(",")
            try:
                for id in id_list:
                    # 先删除 Redis
                    key = await KeyDao.get_key_detail_by_id(query_db, id)
                    await redis.delete(
                        f"{RedisInitKeyConfig.OCR_API_KEY.key}:{key.api_key}"
                    )
                    await KeyDao.delete_key_dao(query_db, KeyModel(id=id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message="删除成功")
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message="传入ID为空")

    @classmethod
    async def key_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取API-KEY详细信息service

        :param query_db: orm对象
        :param id: ID
        :return: ID对应的信息
        """
        key = await KeyDao.get_key_detail_by_id(query_db, id=id)
        if key:
            result = KeyModel(**CamelCaseUtil.transform_result(key))
        else:
            result = KeyModel(**dict())

        return result

    @classmethod
    async def key_is_exist(
        cls,
        request: Request,
        api_key: str = Header(..., alias="Ocr-Api-Key"),
    ):
        key = await request.app.state.redis.get(
            f"{RedisInitKeyConfig.OCR_API_KEY.key}:{api_key}"
        )
        if not key:
            raise AuthException(data="", message="无效的 Ocr-Api-Key")
        return True if key else False

    @classmethod
    async def init_api_key_config_services(cls, query_db: AsyncSession, redis: Redis):
        keys = await redis.keys(f"{RedisInitKeyConfig.OCR_API_KEY.key}:*")
        if keys:
            await redis.delete(*keys)
        api_key_list = await cls.get_key_list_services(
            query_db, KeyPageQueryModel(), is_page=False
        )
        for api_key in api_key_list:
            await redis.set(
                f"{RedisInitKeyConfig.OCR_API_KEY.key}:{api_key['apiKey']}",
                api_key["apiKey"],
            )

    @staticmethod
    async def export_key_list_services(key_list: List):
        """
        导出API-KEY信息service

        :param key_list: API-KEY信息列表
        :return: API-KEY信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            "id": "ID",
            "userId": "用户ID",
            "apiKey": "API-KEY",
        }
        binary_data = ExcelUtil.export_list2excel(key_list, mapping_dict)

        return binary_data
